<template>
  <div>
    <Breadcrumb>
      <Breadcrumb-item href="/">首页</Breadcrumb-item>
      <Breadcrumb-item href="/roles/list">角色列表</Breadcrumb-item>
      <Breadcrumb-item>角色权限</Breadcrumb-item>
    </Breadcrumb>
    <div>

      <Form ref="formRole" :model="formRole" :rules="ruleValidate" :label-width="100">
        <Form-item label="角色" prop="id" v-if="id">
          <Row>
            <Col span="12">
              <Input v-model="id" readonly />
            </Col>
          </Row>
        </Form-item>
        <Form-item label="权限" prop="rolePerms">
          <Tree :data="treeData" show-checkbox  @on-select-change="onTreeNodeChange"></Tree>
        </Form-item>
        <Form-item>
          <Button type="primary" @click="handleSave">保存</Button>
          <Button type="ghost" @click="$router.back()">返回</Button>
        </Form-item>
      </Form>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'

  export default {
    name: 'PermForm',
    components: {
    },
    created () {
      this.id = this.$route.params.id
      // this.id && this.get(this.id)
      this.getPerms()
    },
    data () {
      return {
        id: '',
        formRole: {
          id: ''
        },
        ruleValidate: {
        },
        perms: [],
        perm: '',
        self: this,
        rolePerms: [],
        treeData: [],
        selectedNode: null,
        permColumns: [
          {title: '权限', key: 'id'},
          {title: '名称', key: 'name'},
          {
            title: '操作',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.remove(params.index)
                    }
                  }
                }, '删除')
              ])
            }
          }]
      }
    },
    computed: {
      ...mapState(['users', 'roles'])
    },
    watch: {
      'users.user': {
        handler (newVal) {
          this.$set(this, 'formRole', newVal)
        }
      }
    },
    methods: {
      get (id) {
        this.$store.dispatch('getRolePerms', {id}).then((data) => {
          let treeData = this.makeTree(this.perms)
          let rolePerms = data
          this.treeData = this.toTreeData(treeData, rolePerms)
          this.rolePerms = rolePerms
        })
      },
      toTreeData (treeData, rolePerms) {
        for (var i = 0; i < rolePerms.length; i++) {
          this.checkTreeItem(treeData, rolePerms[i].parent, rolePerms[i].name)
        }
        return treeData
      },
      checkTreeItem (treeData, topName, name) {
        let item = this.findTreeItem(treeData, topName, name)
        if (item) {
          item.checked = true
        }
      },
      searchTreeItem (treeData, name) {
        for (var i = 0; i < treeData.length; i++) {
          let item = this.findItemInChildren(treeData[i])
          if (item) {
            return item
          }
        }
        return null
      },
      makeTreeItem (treeData, topName, name) {
        let topItem = this.makeTopItem(treeData, name)
        let item = this.findItemWithName(topItem, name)
        if (!item) {
          item = {name: name, title: name}
        }
        return item
      },
      findTreeItem (treeData, topName, name) {
        let topItem = this.findTopItem(treeData, topName)
        if (topItem) {
          return this.findItemInChildren(topItem, name)
        }
        return null
      },
      findItemInChildren (treeData, name) {
        for (var i = 0; i < treeData.children.length; i++) {
          if (treeData.children[i].name === name) {
            return treeData.children[i]
          }
        }
        return null
      },
      makeTopItem (treeData, name) {
        let topItem = this.findTopItem(treeData, name)
        if (!topItem) {
          topItem = {expand: false, title: name, name: name, children: []}
          treeData.push(topItem)
        }
        return topItem
      },
      findTopItem (treeData, name) {
        for (var i = 0; i < treeData.length; i++) {
          if (treeData[i].name === name) {
            return treeData[i]
          }
        }
        return null
      },
      makeTree (perms) {
        let treeData = []
        for (var i = 0; i < perms.length; i++) {
          let perm = perms[i]
          let item = {}
          item.name = perm.name
          item.value = perm.id
          item.title = perm.name
          item.checked = false
          let topItem = this.makeTopItem(treeData, perm.parent)
          topItem.children.push(item)
        }
        return treeData
      },
      fromTreeData (treeData) {
        let perms = []
        for (var i = 0; i < treeData.length; i++) {
          let topItem = treeData[i]
          for (var j = 0; j < topItem.children.length; j++) {
            let item = topItem.children[j]
            if (item.checked) {
              perms.push(item.value)
            }
          }
        }
        return perms
      },
      toggleExpand (node) {
        node.expand = !node.expand
      },
      onTreeNodeChange (nodes) {
        if (nodes.length > 0) {
          this.selectedNode = nodes[0]
          this.toggleExpand(this.selectedNode)
        } else {
          this.toggleExpand(this.selectedNode)
          this.selectedNode = null
        }
      },
      show (index) {
      },
      remove (index) {
        let perm = this.rolePerms[index]
        this.$store.dispatch('deleteRolePerm', {
          id: this.id,
          perm: perm.id
        }).then(() => {
          this.rolePerms.splice(index, 1)
        })
      },
      getPerms () {
        this.$store.dispatch('getPerms', {}).then((data) => {
          this.perms = data
          if (this.id) {
            this.get(this.id)
          }
        })
      },
      addRolePerm (perm) {
        this.$store.dispatch('addRolePerm', {id: this.id, perm}).then(() => {
          this.get(this.id)
        })
      },
      handleAddPerm () {
        this.addRolePerm(this.perm)
      },
      resetFields () {
        this.$refs.formRole.resetFields()
      },
      handleSave () {
        this.rolePerms = this.fromTreeData(this.treeData)

        this.$store.dispatch('setRolePerms', {
          role: this.id,
          perms: this.rolePerms
        }).then(() => {
          this.$Message.success('编辑' + '成功！')
          !this.id && this.resetFields()
        })
      }
    }
  }
</script>
